<?php


namespace App\Web\Model;


class Model {

    protected $allowLimit = [1, 2, 3, 4, 5, 10, 20, 50];

    public function __construct() {

    }

    /**
     * 根据页码和每页显示数目，进行分页值获取
     * @param int $pageNum
     * @param int $pageLimit
     * @return array
     */
    public function paginationParameters($pageNum = 1, $pageLimit = 10) {
        $pageNum = intval($pageNum) <= 0 ? 1 : intval($pageNum);
        $pageLimit = in_array($pageLimit, $this->allowLimit) ? $pageLimit : 10;
        $rowFrom = ($pageNum - 1) * $pageLimit;
        $rowTo = $pageNum * $pageLimit;
        return [$pageNum, $rowFrom, $rowTo];
    }

    /**
     * 自动判断查询数字或者字符串
     * @param $searchString
     * @param $stringField
     * @param $idField
     * @param int $limit
     * @return array
     */
    protected function searchStringOrNum($searchString, $stringField, $idField, $limit = 10) {
        //$stringArr = array_filter(explode(',', $searchString));
        $stringArr = array_filter($this->modifySearchArr($searchString));
        foreach ($stringArr as $item) {
            if (!ctype_digit($item)) {
                return ['where' => $stringField . ' like ?', 'var' => ['%' . strtolower($searchString) . '%']];
            }
        }
        $stringArr = array_slice($stringArr, 0, $limit);
        $inFlag = substr(str_repeat('? ,', (count($stringArr))), 0, -1);
        $where = $idField . ' in ( ' . $inFlag . ' )';
        return ['where' => $where, 'var' => $stringArr];
    }

    /*
	*数组ValueToKey转化
	*/
    function arrValueToKey(array &$partArr) {
        $partArr = array_flip($partArr);
        foreach ($partArr as $key => &$item) {
            $item = '';
        }
        unset($item);
    }

    /*
	*数据查询 in 方式拼接
	*/
    function arrAppand(array &$mainArr, array $partArr) {
        $placeTag = '';
        if (empty($partArr)) {
            return $placeTag;
        }

        foreach ($partArr as $key => $item) {
            $mainArr[] = $key;
            $placeTag .= "?,";
        }
        return trim($placeTag, ",");
        //$array3 = array_merge($array1, $array2);
        //echo var_export($array3,true);
    }

    function modifySearchArr($searchArr) {
        $searchArr = str_replace('，', ',', str_replace(' ', ',', $searchArr));
        $searchArr = explode(',', $searchArr);
        $delArr = [''];
        $searchArr = array_diff($searchArr,$delArr);
        $searchArr = array_unique($searchArr);
        return $searchArr;
    }
}